<template>
  <div class="box-border overflow-y-auto relative px-4 py-24 w-full h-full" ref="scrollRef">
    <div class="absolute logo w-[220px] h-[34px] top-10 left-1/2 -translate-x-1/2"></div>
    <van-form ref="formRef" required="auto">
      <van-cell-group inset>
        <van-field
          v-model="deviceName"
          name="deviceName"
          label="设备名："
          placeholder="输入设备名"
          readonly
          :rules="[{ required: true, message: '请输入设备名' }]"
        />
        <van-field
          v-model="inspectionPerson"
          name="inspectionPerson"
          label="巡检人："
          placeholder="输入巡检人"
          readonly
          :rules="[{ required: true, message: '请输入巡检人' }]"
        />
        <van-field
          v-model="inspectionTask"
          is-link
          readonly
          name="inspectionTask"
          label="巡检任务："
          placeholder="巡检设备-巡检时间"
          @click="showTaskPicker = true"
          :rules="[{ required: true, message: '请选择巡检任务' }]"
        />
        <van-popup v-model:show="showTaskPicker" position="bottom">
          <van-picker :columns="columns1" @confirm="onConfirm1" @cancel="showTaskPicker = false" />
        </van-popup>
        <div class="text-sm text-[#323233] p-3 mt-4 font-bold">巡检内容：</div>
        <div class="flex flex-col gap-2">
          <div
            v-for="(item, index) in inspectionContents"
            :key="index"
            class="text-sm text-[#323233] p-3"
          >
            <div class="flex gap-2 items-center">
              <div class="text-[#606266]">项目{{ index + 1 }}：</div>
              <div class="flex-1">{{ item.title }}</div>
            </div>
            <van-field :name="`status-${index}`" label="是否正常：">
              <template #input>
                <van-radio-group v-model="item.status" direction="horizontal">
                  <van-radio name="正常">正常</van-radio>
                  <van-radio name="异常">异常</van-radio>
                </van-radio-group>
              </template>
            </van-field>

            <van-field
              v-model="item.content"
              :name="`content-${index}`"
              rows="2"
              autosize
              type="textarea"
              maxlength="100"
              placeholder="请输入内容"
              show-word-limit
              :rules="item.status === '异常' ? [{ required: true, message: `请输入异常内容（请勿输入“.”、“。”、“ ' ”、“<”、“>”、“{”或“}”等特殊字符）` }] : []"
            />
            <van-field
              :name="`uploader-${index}`"
              :rules="item.status === '异常' ? [{ required: true, message: '请上传照片' }] : []"
            >
              <template #input>
                <van-uploader
                  v-model="item.images"
                  :after-read="(file) => afterRead(file, index)"
                  multiple
                />
              </template>
            </van-field>
            <div class="border1"></div>
          </div>
        </div>
      </van-cell-group>

      <div style="margin: 16px">
        <van-button round block type="primary" @click="onSubmit"> 提交 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { inspectionUploadPhoto, inspectionComplete } from '@/api/api'
import { useUserStore } from '@/stores/user'
import { getDeviceInfo } from '@/api/api'

const userStore = useUserStore()
const deviceName = ref('')
const inspectionPerson = ref('')
const inspection_content = ref('')
const inspectionTask = ref('')
const showTaskPicker = ref(false)
const columns1 = ref([])

const onConfirm1 = ({ selectedOptions }) => {
  console.log('🚀 ~ onConfirm1 ~ selectedOptions:', selectedOptions[0])
  inspectionTask.value = selectedOptions[0]?.text
  inspection_content.value = selectedOptions[0]?.inspection_content

  // 更新巡检内容
  const contentStr = selectedOptions[0]?.inspection_content
  if (contentStr) {
    const contents = contentStr.split(/(?<!\S)\d+\.\s*(.*?)(?=\s+\d+\.|$)/g).filter((item) => item.trim())
    inspectionContents.value = contents.map((item) => ({
      title: item.trim(),
      status: '正常',
      content: '',
      images: []
    }))
  } else {
    inspectionContents.value = [
      {
        title: '内容1',
        status: '正常',
        content: '',
        images: []
      },
      {
        title: '内容2',
        status: '正常',
        content: '',
        images: []
      },
      {
        title: '内容3',
        status: '正常',
        content: '',
        images: []
      }
    ]
  }
  showTaskPicker.value = false
}

const inspectionContents = ref([
  {
    title: '内容1',
    status: '正常',
    content: '',
    images: []
  },
  {
    title: '内容2',
    status: '正常',
    content: '',
    images: []
  },
  {
    title: '内容3',
    status: '正常',
    content: '',
    images: []
  }
])

const afterRead = async (file, index) => {
  console.log(file, index)
  const formData = new FormData()
  formData.append('inspection_photos', file.file)

  try {
    const res = await inspectionUploadPhoto(formData)
    if (res.code === 200) {
      const fileList = inspectionContents.value[index].images
      const currentFile = fileList[fileList.length - 1]
      if (currentFile) {
        currentFile.url = `${import.meta.env.VITE_IMG_URL}${res.photos[0]}`
      }
      console.log('🚀 ~ afterRead ~ fileList:', fileList)
      showSuccessToast('上传成功！')
    } else {
      inspectionContents.value[index].images.pop()
      showFailToast('上传失败！')
    }
  } catch (error) {
    inspectionContents.value[index].images.pop()
    showFailToast('上传失败！')
  }
}

const scrollRef = ref(null)
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      showConfirmDialog({
        title: '确认提交',
        message: '确认要提交巡检信息吗？'
      })
        .then(async () => {
          const processedInspectionContents = inspectionContents.value.map((item) => ({
            title: item.title,
            status: item.status,
            content: item.content,
            images: item.images.length > 0 ? item.images.map((img) => img.url) : []
          }))

          const res = await inspectionComplete({
            task_id: columns1.value.find((item) => item.text === inspectionTask.value)?.value,
            device_name: deviceName.value,
            inspector: inspectionPerson.value,
            inspection_content: inspection_content.value,
            inspection_result: processedInspectionContents
          })
          if (res.code === 200) {
            showSuccessToast('提交成功！')
            inspectionTask.value = ''
            inspectionContents.value = inspectionContents.value.map((item) => ({
              ...item,
              status: '正常',
              content: '',
              images: []
            }))
            formRef.value.resetValidation()
            scrollRef.value.scrollTo({ top: 0, behavior: 'smooth' })
          }
        })
        .catch(() => {
          console.log('用户取消提交')
        })
    })
    .catch((err) => {
      console.log('表单验证失败', err)
      scrollRef.value.scrollTo({ top: 0, behavior: 'smooth' })
    })
}

const formRef = ref(null)

const getDeviceDetails = async () => {
  console.log('🚀 ~ getDeviceDetails ~ userStore.deviceId:', userStore.deviceId)
  try {
    const res = await getDeviceInfo({ id: userStore.deviceId })
    console.log('🚀 ~ getDeviceDetails ~ res:', res)

    if (res.code === 200) {
      deviceName.value = res.data.device_name
    } else {
      showFailToast('获取设备信息失败')
    }
  } catch (error) {
    showFailToast('获取设备信息失败')
  }
}

onMounted(async () => {
  await getDeviceDetails()
  inspectionPerson.value = userStore.username

  // const today = new Date().toISOString().split('T')[0]

  columns1.value = userStore.userTasks
    .filter((task) => task.device_name === deviceName.value)
    // .filter((task) => {
    //   if (task.frequency === '每日') {
    //     return task.date === today
    //   } else if (task.frequency === '单次') {
    //     return true
    //   }
    //   return false
    // })
    .map((task) => {
      let timeRange
      const formatTime = (time) => time.slice(0, 16)
      if (task.frequency === '每日') {
        timeRange = `${task.date}`
      } else if (task.frequency === '单次') {
        timeRange = `${formatTime(task.single_start_time)} - ${formatTime(task.single_end_time)}`
      }
      const contentStr = task.inspection_content
      if (contentStr) {
        const contents = contentStr.split(/(?<!\S)\d+\.\s*(.*?)(?=\s+\d+\.|$)/g).filter((item) => item.trim())
        inspectionContents.value = contents.map((item) => ({
          title: item.trim(),
          status: '正常',
          content: '',
          images: []
        }))
      } else {
        inspectionContents.value = [
          {
            title: '内容1',
            status: '正常',
            content: '',
            images: []
          },
          {
            title: '内容2',
            status: '正常',
            content: '',
            images: []
          },
          {
            title: '内容3',
            status: '正常',
            content: '',
            images: []
          }
        ]
      }
      return {
        text: `${task.device_name} - ${timeRange}`,
        value: task.task_id,
        inspection_content: task.inspection_content
      }
    })
})
</script>

<style lang="scss" scoped>
.border1 {
  box-shadow: 0 0 0 0.5px black；;
}
:deep(.van-field__label) {
  width: 120px;
}

:deep(.van-form) {
  background-color: transparent;
}
:deep(.van-cell-group--inset) {
  background-color: transparent;
}
:deep(.van-cell) {
  background-color: transparent;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);

  &:last-child {
    border-bottom: none;
  }
}

:deep(.van-field__control:focus) {
  border-color: rgba(0, 0, 0, 0.1);
}

:deep(.van-picker-column) {
  font-size: 14px !important;
}
:deep(.van-field__label) {
  width: 80px;
}
.logo {
  background-image: url('../assets/images/logo.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
</style>
